# -*- coding: utf-8 -*-
import logging, passwords
import os, sys, logging
# Add parent folder to sys.path, so we can import boot.
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't add parent_dir multiple
# times.
parent_dir = os.path.abspath(os.path.dirname(__file__))
logging.info('parent_dir: %s' % parent_dir)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

# Google App Engine imports.
from google.appengine.ext.webapp import util

# Remove the standard version of Django
if 'django' in sys.modules and sys.modules['django'].VERSION < (1, 2):
    for k in [k for k in sys.modules
              if k.startswith('django\.') or k == 'django']:
        del sys.modules[k]

from djangoappengine import boot
boot.setup_threading()
boot.setup_project()
boot.setup_logging()
boot.setup_env()

import django.core.handlers.wsgi
from django.conf import settings
os.environ.update(boot.env_ext)


from waveapi import events
from waveapi import element
from waveapi import robot
from waveapi import appengine_robot_runner
from djapp import views, controller, models
from djapp.wave import *
from google.appengine.api import memcache

def OnWaveletSelfAdded(event, wavelet):
  """Invoked when the robot has been added."""
  #wavelet.root_blip.all().clear_annotation('level')
  w = WaveEntry(wavelet.wave_id, wavelet.title or u'<no title>', wavelet.tags.serialize())
  view.add_wave(w, level = c.get_level_dict(), category_list = c.get_user_categories(), 
                ext_tag = c.get_extended_tag_dict())

def OnWaveletSelfRemoved(event, wavelet):
  logging.info("OnWaveletSelfRemoved called")
  w = WaveEntry(wavelet.wave_id, wavelet.title, wavelet.tags.serialize())
  view.delete_wave(w, level = c.get_level_dict(), category_list = c.get_user_categories(), 
                   ext_tag = c.get_extended_tag_dict())
  
def OnWaveletTagsChanged(event, wavelet):
  w = models.Wave.objects.filter(wave_id = wavelet.wave_id)
  if w:
      old_wave = WaveEntry(w[0].wave_id, w[0].title, w[0].tags)
      view.delete_wave(old_wave, level = c.get_level_dict(), category_list = c.get_user_categories(), 
                       ext_tag = c.get_extended_tag_dict())
  new_wave = WaveEntry(wavelet.wave_id, wavelet.title or u'<no title>', wavelet.tags.serialize())
  view.add_wave(new_wave, level = c.get_level_dict(), category_list = c.get_user_categories(), 
                ext_tag = c.get_extended_tag_dict())
  
if __name__ == '__main__':
  myRobot = robot.Robot(passwords.ROBOT_NAME,
      image_url = passwords.IMAGE_URL,
      profile_url = passwords.PROFILE_URL)
  view = memcache.get("view") 
  c = memcache.get("controller")
  if True:
    c = controller.Controller()
    cat = c.get_user_categories()
    lvl = c.get_level_dict()
    extended_tag_dict = c.get_extended_tag_dict()
    view = views.View()
    if not memcache.add("view", view, 600):
      memcache.set("view", view, 600)
      logging.error("Memcache [view] add failed.") 
  myRobot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, 
                      server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc')
  myRobot.register_handler(events.WaveletSelfRemoved, OnWaveletSelfRemoved)
  myRobot.register_handler(events.WaveletTagsChanged, OnWaveletTagsChanged)
  myRobot.register_handler(events.WaveletSelfAdded, OnWaveletSelfAdded)
  appengine_robot_runner.run(myRobot)
